{% extends "base.html" %}

{% block title %}学生管理 - IT课程数据分析系统{% endblock %}

{% block extra_css %}
<style>
    .course-selector {
        margin-bottom: 1.5rem;
        padding: 1rem;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    
    .course-selector select {
        padding: 0.5rem 1rem;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        font-size: 1rem;
        min-width: 300px;
    }
    
    .students-table {
        width: 100%;
        border-collapse: collapse;
    }
    
    .students-table th,
    .students-table td {
        padding: 0.75rem;
        text-align: left;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .students-table th {
        background: #f8f9fa;
        font-weight: 600;
        color: #2c3e50;
        position: sticky;
        top: 0;
        z-index: 10;
    }
    
    .students-table tr:hover {
        background: #f8f9fa;
    }
    
    .action-btn {
        padding: 0.25rem 0.75rem;
        margin: 0 0.25rem;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.85rem;
    }
    
    .btn-edit {
        background: #3498db;
        color: white;
    }
    
    .badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        border-radius: 12px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    
    .badge-success {
        background: #d4edda;
        color: #155724;
    }
    
    .badge-warning {
        background: #fff3cd;
        color: #856404;
    }
    
    .badge-danger {
        background: #f8d7da;
        color: #721c24;
    }
    
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        z-index: 1000;
    }
    
    .modal-content {
        background: white;
        max-width: 600px;
        margin: 5% auto;
        padding: 2rem;
        border-radius: 8px;
    }
    
    .form-group {
        margin-bottom: 1rem;
    }
    
    .form-group label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 500;
    }
    
    .form-group input {
        width: 100%;
        padding: 0.5rem;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
    }
</style>
{% endblock %}

{% block content %}
<h2 style="margin-bottom:1.5rem;">学生管理</h2>

<div class="course-selector">
    <label style="margin-right:1rem;font-weight:500;">选择课程：</label>
    <select id="course-select" onchange="loadStudents()">
        <option value="">请选择课程</option>
    </select>
    <span id="student-count" style="margin-left:1rem;color:#7f8c8d;"></span>
</div>

<div class="card" id="students-card" style="display:none;">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;">
        <h3>学生列表</h3>
        <div style="display:flex;gap:1rem;align-items:center;">
            <input type="text" id="search-input" placeholder="搜索学生..." style="padding:0.5rem;border:1px solid #e0e0e0;border-radius:4px;width:250px;">
            <button class="btn btn-success" id="batch-import-btn" onclick="showBatchImportModal()" style="display:none;">
                <i class="fas fa-file-upload"></i> 批量导入
            </button>
            <button class="btn btn-primary" id="add-student-btn" onclick="showAddStudentModal()" style="display:none;">
                <i class="fas fa-user-plus"></i> 添加学生
            </button>
        </div>
    </div>
    
    <div style="max-height:600px;overflow-y:auto;">
        <table class="students-table">
            <thead>
                <tr>
                    <th>学号</th>
                    <th>姓名</th>
                    <th>邮箱</th>
                    <th>总成绩</th>
                    <th>平时</th>
                    <th>考试</th>
                    <th>出勤率</th>
                    <th>等级</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="students-tbody">
            </tbody>
        </table>
    </div>
</div>

<!-- 添加学生模态框 -->
<div id="add-student-modal" class="modal">
    <div class="modal-content" style="max-width: 700px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.5rem;">
            <h3>添加学生到课程</h3>
            <span class="close" onclick="closeAddStudentModal()" style="font-size:1.5rem;cursor:pointer;">&times;</span>
        </div>
        
        <div class="form-group">
            <label>搜索学生</label>
            <input type="text" id="student-search" placeholder="输入学号、姓名或邮箱搜索..." 
                   oninput="searchStudents()" style="width:100%;padding:0.75rem;border:1px solid #e0e0e0;border-radius:4px;">
        </div>
        
        <div id="search-results" style="max-height:400px;overflow-y:auto;margin-top:1rem;">
            <p style="text-align:center;color:#7f8c8d;padding:2rem;">请输入关键词搜索学生</p>
        </div>
        
        <div style="margin-top:1rem;text-align:right;">
            <button class="btn btn-secondary" onclick="closeAddStudentModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 批量导入模态框 -->
<div id="batch-import-modal" class="modal">
    <div class="modal-content" style="max-width: 600px; max-height: 85vh; overflow-y: auto;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;">
            <h3 style="margin:0;">批量导入学生</h3>
            <span class="close" onclick="closeBatchImportModal()" style="font-size:1.5rem;cursor:pointer;">&times;</span>
        </div>
        
        <div style="background:#f8f9fa;padding:0.8rem;border-radius:4px;margin-bottom:1rem;">
            <h4 style="margin:0 0 0.5rem 0;color:#2c3e50;font-size:0.95rem;">📋 导入说明</h4>
            <ul style="margin:0;padding-left:1.5rem;color:#7f8c8d;line-height:1.6;font-size:0.9rem;">
                <li>支持 <strong>CSV</strong> 或 <strong>Excel</strong> (.xlsx/.xls) 文件</li>
                <li>必须包含 <strong>student_id</strong> 列（学号）</li>
                <li>系统将自动跳过已存在的学生</li>
                <li id="max-students-info">课程人数上限：<span id="max-students-display"></span>人</li>
            </ul>
        </div>
        
        <div style="background:#fff3cd;padding:0.8rem;border-radius:4px;margin-bottom:1rem;border-left:4px solid #ffc107;">
            <p style="margin:0;color:#856404;font-size:0.9rem;">
                <i class="fas fa-download"></i> 
                <a href="javascript:void(0);" onclick="downloadTemplate(); return false;" style="color:#856404;text-decoration:underline;font-weight:600;">下载模板文件</a>
            </p>
        </div>
        
        <form id="batch-import-form">
            <div class="form-group">
                <label style="display:block;margin-bottom:0.5rem;font-weight:600;">选择文件</label>
                <div style="position:relative;">
                    <input type="file" id="import-file" accept=".csv,.xlsx,.xls" required
                           style="display:none;"
                           onchange="updateFileName(this)">
                    <button type="button" onclick="document.getElementById('import-file').click()" 
                            style="width:100%;padding:0.75rem;border:2px dashed #e0e0e0;border-radius:4px;cursor:pointer;font-size:0.9rem;background:white;text-align:left;color:#666;">
                        <i class="fas fa-upload"></i> 选择文件
                    </button>
                </div>
                <small id="file-name-display" style="color:#7f8c8d;display:block;margin-top:0.5rem;font-size:0.85rem;">未选择任何文件</small>
            </div>
            
            <div id="import-progress" style="display:none;margin:1rem 0;">
                <div style="background:#e0e0e0;height:4px;border-radius:2px;overflow:hidden;">
                    <div id="progress-bar" style="background:#27ae60;height:100%;width:0;transition:width 0.3s;"></div>
                </div>
                <p id="progress-text" style="text-align:center;margin-top:0.5rem;color:#7f8c8d;font-size:0.9rem;"></p>
            </div>
            
            <div id="import-result" style="display:none;margin:1rem 0;padding:1rem;border-radius:4px;font-size:0.9rem;"></div>
            
            <div style="margin-top:1.5rem;text-align:right;display:flex;gap:0.5rem;justify-content:flex-end;">
                <button type="button" class="btn btn-secondary" onclick="closeBatchImportModal()">取消</button>
                <button type="submit" class="btn btn-success" id="import-submit-btn">
                    <i class="fas fa-upload"></i> 开始导入
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 编辑成绩模态框 -->
<div id="grade-modal" class="modal">
    <div class="modal-content">
        <h3>编辑学生成绩</h3>
        <div id="student-info" style="background:#f8f9fa;padding:1rem;border-radius:4px;margin-bottom:1rem;">
            <!-- 学生信息 -->
        </div>
        
        <form id="grade-form" onsubmit="return false;">
            <input type="hidden" id="edit-student-id">
            <input type="hidden" id="edit-course-id">
            
            <div class="form-group">
                <label>总成绩 (0-100)</label>
                <input type="number" id="score" min="0" max="100" step="0.01">
            </div>
            
            <div class="form-group">
                <label>平时成绩 (0-100)</label>
                <input type="number" id="midterm-score" min="0" max="100" step="0.01">
            </div>
            
            <div class="form-group">
                <label>考试成绩 (0-100)</label>
                <input type="number" id="final-score" min="0" max="100" step="0.01">
            </div>
            
            <div class="form-group">
                <label>出勤次数</label>
                <input type="number" id="attended" min="0">
            </div>
            
            <div class="form-group">
                <label>总课时</label>
                <input type="number" id="total-classes" min="0" readonly style="background:#e9ecef;">
            </div>
            
            <div class="form-group">
                <label>状态</label>
                <select id="status">
                    <option value="enrolled">在读</option>
                    <option value="completed">已完成</option>
                    <option value="dropped">已退课</option>
                </select>
            </div>
            
            <div style="display:flex;gap:1rem;margin-top:1.5rem;">
                <button type="button" class="btn btn-primary" onclick="saveGrade()" style="flex:1;">保存</button>
                <button type="button" class="btn btn-danger" onclick="closeModal()" style="flex:1;">取消</button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let currentCourseId = null;
    let allStudents = [];
    let canEditCourse = false;
    
    async function loadCourses() {
        try {
            const data = await apiRequest('/teacher/my-courses');
            
            if (data.success) {
                const courses = data.data;
                const select = document.getElementById('course-select');
                
                select.innerHTML = '<option value="">请选择课程</option>' + 
                    courses.map(c => `
                        <option value="${c.id}" data-max-students="${c.max_students || ''}">${c.name} (${c.code}) - ${c.total_students}人</option>
                    `).join('');
            }
        } catch (error) {
            showAlert('加载课程失败: ' + error.message, 'error');
        }
    }
    
    async function loadStudents() {
        const courseId = document.getElementById('course-select').value;
        
        if (!courseId) {
            document.getElementById('students-card').style.display = 'none';
            return;
        }
        
        currentCourseId = courseId;
        
        try {
            const data = await apiRequest(`/teacher/courses/${courseId}/students`);
            
            if (data.success) {
                allStudents = data.data.students;
                document.getElementById('student-count').textContent = `共 ${allStudents.length} 名学生`;
                document.getElementById('students-card').style.display = 'block';
                
                // 显示/隐藏添加学生和批量导入按钮（只有自己的课程才能添加）
                canEditCourse = data.data.can_edit || false;
                const addBtn = document.getElementById('add-student-btn');
                const batchImportBtn = document.getElementById('batch-import-btn');
                if (canEditCourse) {
                    addBtn.style.display = 'inline-block';
                    batchImportBtn.style.display = 'inline-block';
                } else {
                    addBtn.style.display = 'none';
                    batchImportBtn.style.display = 'none';
                }
                
                renderStudents(allStudents);
            }
        } catch (error) {
            showAlert('加载学生失败: ' + error.message, 'error');
        }
    }
    
    function renderStudents(students) {
        const tbody = document.getElementById('students-tbody');
        
        if (students.length === 0) {
            tbody.innerHTML = '<tr><td colspan="10" style="text-align:center;color:#7f8c8d;">暂无学生</td></tr>';
            return;
        }
        
        tbody.innerHTML = students.map(s => {
            const isRisk = (s.score && s.score < 60) || (s.attendance_rate && s.attendance_rate < 70);
            
            return `
                <tr style="${isRisk ? 'background:#fee;' : ''}">
                    <td>${s.student_id || '-'}</td>
                    <td>
                        ${s.last_name || ''}${s.first_name || ''}
                        ${isRisk ? '<span style="color:#e74c3c;">⚠️</span>' : ''}
                    </td>
                    <td>${s.email || '-'}</td>
                    <td>
                        <strong style="color:${getScoreColor(s.score)}">
                            ${s.score ? s.score.toFixed(2) : '-'}
                        </strong>
                    </td>
                    <td>${s.midterm_score ? s.midterm_score.toFixed(2) : '-'}</td>
                    <td>${s.final_score ? s.final_score.toFixed(2) : '-'}</td>
                    <td style="color:${getAttendanceColor(s.attendance_rate)}">
                        ${s.attendance_rate ? s.attendance_rate.toFixed(1) + '%' : '-'}
                    </td>
                    <td><span class="badge badge-${getGradeBadge(s.letter_grade)}">${s.letter_grade || '-'}</span></td>
                    <td><span class="badge badge-${getStatusBadge(s.status)}">${getStatusText(s.status)}</span></td>
                    <td>
                        ${canEditCourse ? `
                            <button class="action-btn btn-edit" onclick="editGrade(${s.id}, ${s.student_course_id})">编辑成绩</button>
                            <button class="action-btn btn-danger" onclick="removeStudentFromCourse(${s.id}, '${s.last_name}${s.first_name}')" style="background:#e74c3c;color:white;">移除</button>
                        ` : `
                            <button class="action-btn" style="background:#95a5a6;color:white;cursor:not-allowed;" disabled>仅查看</button>
                        `}
                    </td>
                </tr>
            `;
        }).join('');
    }
    
    function editGrade(studentId, studentCourseId) {
        const student = allStudents.find(s => s.id === studentId);
        if (!student) return;
        
        document.getElementById('edit-student-id').value = studentId;
        document.getElementById('edit-course-id').value = currentCourseId;
        
        document.getElementById('student-info').innerHTML = `
            <strong>${student.last_name}${student.first_name}</strong> (${student.student_id})<br>
            <span style="color:#7f8c8d;font-size:0.9rem;">${student.email}</span>
        `;
        
        document.getElementById('score').value = student.score || '';
        document.getElementById('midterm-score').value = student.midterm_score || '';
        document.getElementById('final-score').value = student.final_score || '';
        document.getElementById('attended').value = student.attended || '';
        document.getElementById('total-classes').value = student.total_classes || 48;
        document.getElementById('status').value = student.status || 'enrolled';
        
        document.getElementById('grade-modal').style.display = 'block';
    }
    
    async function saveGrade() {
        try {
            const studentId = document.getElementById('edit-student-id').value;
            const courseId = document.getElementById('edit-course-id').value;
            
            const gradeData = {
                score: parseFloat(document.getElementById('score').value) || null,
                midterm_score: parseFloat(document.getElementById('midterm-score').value) || null,
                final_score: parseFloat(document.getElementById('final-score').value) || null,
                attended: parseInt(document.getElementById('attended').value) || null,
                status: document.getElementById('status').value
            };
            
            const data = await apiRequest(`/teacher/courses/${courseId}/students/${studentId}/grade`, {
                method: 'PUT',
                body: JSON.stringify(gradeData)
            });
            
            if (data.success) {
                showAlert('成绩更新成功', 'success');
                closeModal();
                loadStudents();
            }
        } catch (error) {
            showAlert('保存失败: ' + error.message, 'error');
        }
    }
    
    function closeModal() {
        document.getElementById('grade-modal').style.display = 'none';
    }
    
    function getScoreColor(score) {
        if (!score) return '#7f8c8d';
        if (score >= 90) return '#27ae60';
        if (score >= 80) return '#2ecc71';
        if (score >= 70) return '#3498db';
        if (score >= 60) return '#f39c12';
        return '#e74c3c';
    }
    
    function getAttendanceColor(rate) {
        if (!rate) return '#7f8c8d';
        if (rate >= 90) return '#27ae60';
        if (rate >= 80) return '#2ecc71';
        if (rate >= 70) return '#f39c12';
        return '#e74c3c';
    }
    
    function getGradeBadge(grade) {
        if (!grade) return '';
        if (grade === 'A' || grade === 'B') return 'success';
        if (grade === 'C' || grade === 'D') return 'warning';
        return 'danger';
    }
    
    function getStatusBadge(status) {
        if (status === 'completed') return 'success';
        if (status === 'enrolled') return 'warning';
        return 'danger';
    }
    
    function getStatusText(status) {
        const map = {
            'enrolled': '在读',
            'completed': '已完成',
            'dropped': '已退课'
        };
        return map[status] || status;
    }
    
    // 搜索功能
    document.getElementById('search-input')?.addEventListener('input', (e) => {
        const keyword = e.target.value.toLowerCase();
        const filtered = allStudents.filter(s => 
            (s.student_id && s.student_id.toLowerCase().includes(keyword)) ||
            (s.last_name && s.last_name.toLowerCase().includes(keyword)) ||
            (s.first_name && s.first_name.toLowerCase().includes(keyword)) ||
            (s.email && s.email.toLowerCase().includes(keyword))
        );
        renderStudents(filtered);
    });
    
    // 页面加载
    window.addEventListener('DOMContentLoaded', () => {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
        if (userInfo.role !== 'teacher') {
            showAlert('权限不足', 'error');
            setTimeout(() => window.location.href = '/', 2000);
            return;
        }
        
        loadCourses();
    });
    
    // 点击模态框外部关闭
    window.onclick = function(event) {
        const gradeModal = document.getElementById('grade-modal');
        const addModal = document.getElementById('add-student-modal');
        const batchImportModal = document.getElementById('batch-import-modal');
        if (event.target === gradeModal) {
            closeModal();
        }
        if (event.target === addModal) {
            closeAddStudentModal();
        }
        if (event.target === batchImportModal) {
            closeBatchImportModal();
        }
    }
    
    // 显示添加学生模态框
    function showAddStudentModal() {
        if (!currentCourseId) {
            showAlert('请先选择课程', 'warning');
            return;
        }
        document.getElementById('add-student-modal').style.display = 'block';
        document.getElementById('student-search').value = '';
        document.getElementById('search-results').innerHTML = '<p style="text-align:center;color:#7f8c8d;padding:2rem;">请输入关键词搜索学生</p>';
    }
    
    // 关闭添加学生模态框
    function closeAddStudentModal() {
        document.getElementById('add-student-modal').style.display = 'none';
    }
    
    // 搜索学生
    let searchTimeout = null;
    async function searchStudents() {
        const query = document.getElementById('student-search').value.trim();
        
        if (query.length < 2) {
            document.getElementById('search-results').innerHTML = '<p style="text-align:center;color:#7f8c8d;padding:2rem;">请输入至少2个字符</p>';
            return;
        }
        
        // 防抖
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(async () => {
            try {
                const data = await apiRequest(`/teacher/students/search?q=${encodeURIComponent(query)}&course_id=${currentCourseId}`);
                
                if (data.success) {
                    const students = data.data;
                    const resultsDiv = document.getElementById('search-results');
                    
                    if (students.length === 0) {
                        resultsDiv.innerHTML = '<p style="text-align:center;color:#7f8c8d;padding:2rem;">未找到匹配的学生</p>';
                        return;
                    }
                    
                    resultsDiv.innerHTML = students.map(s => `
                        <div style="display:flex;justify-content:space-between;align-items:center;padding:1rem;border-bottom:1px solid #e0e0e0;">
                            <div>
                                <div style="font-weight:500;">${s.name}</div>
                                <div style="font-size:0.85rem;color:#7f8c8d;">
                                    学号: ${s.student_id || '-'} | 邮箱: ${s.email || '-'}
                                </div>
                            </div>
                            ${s.enrolled ? 
                                '<span class="badge badge-success">已添加</span>' : 
                                `<button class="btn btn-primary btn-sm" onclick="addStudentToCourse(${s.id}, '${s.name}')">添加</button>`
                            }
                        </div>
                    `).join('');
                }
            } catch (error) {
                showAlert('搜索失败: ' + error.message, 'error');
            }
        }, 300);
    }
    
    // 添加学生到课程
    async function addStudentToCourse(studentId, studentName) {
        if (!confirm(`确定要将 ${studentName} 添加到课程中吗？`)) {
            return;
        }
        
        try {
            const data = await apiRequest(`/teacher/courses/${currentCourseId}/students`, {
                method: 'POST',
                body: JSON.stringify({ student_id: studentId })
            });
            
            if (data.success) {
                showAlert('学生添加成功！', 'success');
                closeAddStudentModal();
                loadStudents(); // 重新加载学生列表
            } else {
                showAlert(data.error || '添加失败', 'error');
            }
        } catch (error) {
            showAlert('添加失败: ' + error.message, 'error');
        }
    }
    
    // 从课程移除学生
    async function removeStudentFromCourse(studentId, studentName) {
        if (!confirm(`确定要将 ${studentName} 从课程中移除吗？此操作将删除该学生的所有成绩记录！`)) {
            return;
        }
        
        try {
            const data = await apiRequest(`/teacher/courses/${currentCourseId}/students/${studentId}`, {
                method: 'DELETE'
            });
            
            if (data.success) {
                showAlert('学生已移除', 'success');
                loadStudents(); // 重新加载学生列表
            } else {
                showAlert(data.error || '移除失败', 'error');
            }
        } catch (error) {
            showAlert('移除失败: ' + error.message, 'error');
        }
    }
    
    // 批量导入相关函数
    function showBatchImportModal() {
        if (!currentCourseId) {
            showAlert('请先选择课程', 'warning');
            return;
        }
        
        // 显示课程最大学生数
        const courseSelector = document.getElementById('course-select');
        const selectedOption = courseSelector.options[courseSelector.selectedIndex];
        const maxStudents = selectedOption.dataset.maxStudents;
        
        // 如果没有设置max_students或为null，显示"不限人数"
        const maxStudentsInfo = document.getElementById('max-students-info');
        if (!maxStudents || maxStudents === 'null' || maxStudents === 'None') {
            maxStudentsInfo.innerHTML = '课程人数：<strong style="color:#27ae60;">不限人数</strong>';
        } else {
            maxStudentsInfo.innerHTML = '课程人数上限：<span id="max-students-display">' + maxStudents + '</span>人';
        }
        
        // 重置表单
        document.getElementById('batch-import-form').reset();
        document.getElementById('import-progress').style.display = 'none';
        document.getElementById('import-result').style.display = 'none';
        
        document.getElementById('batch-import-modal').style.display = 'flex';
    }
    
    function closeBatchImportModal() {
        document.getElementById('batch-import-modal').style.display = 'none';
    }
    
    // 下载模板文件
    function downloadTemplate() {
        // 创建CSV内容
        const csvContent = 'student_id\n2021001\n2021002\n2021003';
        const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', '学生导入模板.csv');
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        return false;
    }
    
    // 更新文件名显示
    function updateFileName(input) {
        const fileNameDisplay = document.getElementById('file-name-display');
        if (input.files && input.files.length > 0) {
            const fileName = input.files[0].name;
            const fileSize = (input.files[0].size / 1024).toFixed(2);
            fileNameDisplay.textContent = `已选择: ${fileName} (${fileSize} KB)`;
            fileNameDisplay.style.color = '#27ae60';
        } else {
            fileNameDisplay.textContent = '未选择任何文件';
            fileNameDisplay.style.color = '#7f8c8d';
        }
    }
    
    // 处理批量导入
    document.getElementById('batch-import-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const fileInput = document.getElementById('import-file');
        const file = fileInput.files[0];
        
        if (!file) {
            showAlert('请选择文件', 'warning');
            return;
        }
        
        // 显示进度
        document.getElementById('import-progress').style.display = 'block';
        document.getElementById('progress-bar').style.width = '0%';
        document.getElementById('progress-text').textContent = '正在上传文件...';
        document.getElementById('import-submit-btn').disabled = true;
        document.getElementById('import-result').style.display = 'none';
        
        // 创建FormData
        const formData = new FormData();
        formData.append('file', file);
        
        try {
            // 模拟进度
            document.getElementById('progress-bar').style.width = '30%';
            document.getElementById('progress-text').textContent = '正在解析文件...';
            
            const response = await fetch(`/api/v1/teacher/courses/${currentCourseId}/students/batch-import`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                },
                body: formData
            });
            
            document.getElementById('progress-bar').style.width = '70%';
            document.getElementById('progress-text').textContent = '正在处理数据...';
            
            const data = await response.json();
            
            document.getElementById('progress-bar').style.width = '100%';
            document.getElementById('progress-text').textContent = '导入完成！';
            
            // 显示结果
            const resultDiv = document.getElementById('import-result');
            resultDiv.style.display = 'block';
            
            if (data.success) {
                const result = data.data;
                resultDiv.style.background = '#d4edda';
                resultDiv.style.borderLeft = '4px solid #28a745';
                resultDiv.innerHTML = `
                    <h4 style="margin:0 0 0.5rem 0;color:#155724;">✅ 导入成功</h4>
                    <div style="color:#155724;line-height:1.8;">
                        <p style="margin:0.25rem 0;">• 总计: ${result.total} 条记录</p>
                        <p style="margin:0.25rem 0;">• 成功: ${result.success} 人</p>
                        <p style="margin:0.25rem 0;">• 失败: ${result.failed} 人</p>
                        <p style="margin:0.25rem 0;">• 跳过: ${result.skipped} 人</p>
                        ${result.errors && result.errors.length > 0 ? `
                            <details style="margin-top:0.5rem;">
                                <summary style="cursor:pointer;font-weight:600;">查看错误详情</summary>
                                <ul style="margin:0.5rem 0;padding-left:1.5rem;font-size:0.85rem;">
                                    ${result.errors.map(err => `<li>${err}</li>`).join('')}
                                </ul>
                            </details>
                        ` : ''}
                    </div>
                `;
                
                // 重新加载学生列表
                setTimeout(() => {
                    loadStudents();
                    if (result.failed === 0 && result.skipped === 0) {
                        closeBatchImportModal();
                    }
                }, 2000);
            } else {
                resultDiv.style.background = '#f8d7da';
                resultDiv.style.borderLeft = '4px solid #dc3545';
                resultDiv.innerHTML = `
                    <h4 style="margin:0 0 0.5rem 0;color:#721c24;">❌ 导入失败</h4>
                    <p style="margin:0;color:#721c24;">${data.error || '未知错误'}</p>
                `;
            }
            
        } catch (error) {
            document.getElementById('progress-bar').style.width = '100%';
            document.getElementById('progress-bar').style.background = '#dc3545';
            document.getElementById('progress-text').textContent = '导入失败！';
            
            const resultDiv = document.getElementById('import-result');
            resultDiv.style.display = 'block';
            resultDiv.style.background = '#f8d7da';
            resultDiv.style.borderLeft = '4px solid #dc3545';
            resultDiv.innerHTML = `
                <h4 style="margin:0 0 0.5rem 0;color:#721c24;">❌ 网络错误</h4>
                <p style="margin:0;color:#721c24;">${error.message}</p>
            `;
        } finally {
            document.getElementById('import-submit-btn').disabled = false;
        }
    });
</script>
{% endblock %}

